package cn.zy.framework.helper;

import cn.zy.framework.annotation.Inject;
import cn.zy.framework.util.ReflectionUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @Author: Administrator
 * @Description:
 * @Date: Created in 17:40 2021/9/10
 * @Modified By:
 * @version: 1.0
 * 依赖注入助手
 */
public final class IocHelper {

	static {
		//获取所有的 Bean 类与 Bean 实例之间的映射关系
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();

		if (MapUtils.isNotEmpty(beanMap)) {
			//遍历 beanMap
			for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
				//从 beanMap 中获取 Bean 类与 Bean 实例
				Class<?> beanClass = beanEntry.getKey();
				Object beanInstance = beanEntry.getValue();
				//获取 Bean 类定义的所有成员变量
				Field[] beanFields = beanClass.getDeclaredFields();
				if (ArrayUtils.isNotEmpty(beanFields)) {
					for (Field field : beanFields) {
						if (field.isAnnotationPresent(Inject.class)) {
							//在 beanMap 中获取 beanField 对应的实例
							Class<?> beanFieldClass = field.getType();
							Object beanFieldInstance = beanMap.get(beanFieldClass);
							if (beanFieldInstance != null) {
								//通过反射初始化 BeanField 的值
								ReflectionUtil.setField(beanInstance, field, beanFieldInstance);
							}
						}
					}
				}


			}
		}


	}

}
